package com.example.user1.controller;

import com.example.user1.enums.VerifyCodeTypeEnum;
import com.example.user1.exception.BusinessException;
import com.example.user1.service.VerifyCodeService;
import com.example.user1.vo.Result;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.function.Supplier;

import static com.example.user1.enums.ErrorEnum.SERVICE_NOT_EXIST;

@RestController
@RequestMapping("/verifyCode")
@RequiredArgsConstructor
public class VerifyCodeController {
    private final List<VerifyCodeService> verifyCodeServices;
    @GetMapping("/image/{id}")
    public void generateImage(@PathVariable("id") String clientId){
        VerifyCodeService verifyCodeService = find(VerifyCodeTypeEnum.IMAGE);
        verifyCodeService.generate(clientId);
    }

    @GetMapping("/phone/{phone}")
    public Result<Void> generatePhone(@PathVariable("phone") String phone){
        VerifyCodeService verifyCodeService = find(VerifyCodeTypeEnum.PHONE);
        verifyCodeService.generate(phone);
        return Result.success();
    }

    @SneakyThrows
    public VerifyCodeService find(VerifyCodeTypeEnum verifyCodeTypeEnum) {
        return verifyCodeServices.stream().filter(x -> x.type().equals(verifyCodeTypeEnum)).findFirst().orElseThrow((Supplier<? extends Throwable>) ()->{
            return new BusinessException(SERVICE_NOT_EXIST);
        });
    }
}
